package com.ing5.BL.android.cinece;

import com.ing5.BL.android.cinece.api.client.GetSearch;
import com.ing5.BL.android.cinece.api.model.SearchResults;
import com.ing5.BL.android.cinece.util.CacheClient;

import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.Toast;
import android.widget.SearchView.OnQueryTextListener;

public class SearchFragment extends Fragment {

	private SearchView searchView;
	private ListView listView;
	private ProgressBar progBarSearch;
	private MovieListAdapter movieAdapter;
	private OnItemSelectedListener listener;
	private SearchResults searchResults;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(savedInstanceState != null)
			if(savedInstanceState.containsKey("searchResults"))
				searchResults = (SearchResults) savedInstanceState.getSerializable("searchResults");
		return inflater.inflate(R.layout.activity_main, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		listView = (ListView) getView().findViewById(R.id.listView);
		progBarSearch = (ProgressBar) getView()
				.findViewById(R.id.progBarSearch);

		progBarSearch.setVisibility(View.GONE);
		listView.setVisibility(View.GONE);

		searchView = (SearchView) getView().findViewById(R.id.search);
		searchView.setOnQueryTextListener(new OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String query) {
				if (query.length() != 0) {
					searchView.clearFocus();
					new GetResultTask().execute(new GetSearch(query));
					return true;
				}
				return false;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				return false;
			}
		});

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long arg3) {
				updateDetail(searchResults.getResultList().get(position)
						.getId());
			}
		});
	}
	
	@Override
	public void onStart() {
		super.onStart();
		if (getFragmentManager().findFragmentById(R.id.detailFragment) != null) {
			listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);			
		}
		if(searchResults != null) {
			adapteList(searchResults);
			listView.setVisibility(View.VISIBLE);
			searchView.clearFocus();
		}
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable("searchResults", searchResults);
	}

	public void adapteList(SearchResults results) {
		movieAdapter = new MovieListAdapter(this.getActivity(),
				results.getResultList());
		listView.setAdapter(movieAdapter);
	}

	public void noResultToast() {
		Toast.makeText(this.getActivity(), "No Result Found", Toast.LENGTH_LONG).show();
	}

	public interface OnItemSelectedListener {
		public void onMovieSelected(String id);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof OnItemSelectedListener) {
			listener = (OnItemSelectedListener) activity;
		} else {
			throw new ClassCastException(activity.toString()
					+ " must implemenet SearchFragment.OnItemSelectedListener");
		}
	}

	public void updateDetail(String id) {
		listener.onMovieSelected(id);
	}

	class GetResultTask extends
			AsyncTask<GetSearch, SearchResults, SearchResults> {

		@Override
		protected void onPreExecute() {
			listView.setVisibility(View.GONE);
			progBarSearch.setVisibility(View.VISIBLE);
			progBarSearch.bringToFront();
			super.onPreExecute();
		}

		@Override
		protected SearchResults doInBackground(GetSearch... getSearch) {
			SearchResults results = null;

			try {
				results = new CacheClient(getActivity().getApplicationContext())
						.load(getSearch[0]);
			} catch (Exception e) {
				Log.e("DEBUG", "AsyncTask - Load Failed");
			}
			return results;
		}

		@Override
		protected void onPostExecute(SearchResults results) {
			if (results != null) {
				progBarSearch.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				if (!results.getResultList().isEmpty()) {
					searchResults = results;
					adapteList(results);
				}

			} else {
				progBarSearch.setVisibility(View.GONE);
				listView.setVisibility(View.GONE);
				noResultToast();
			}
		}
	}
}
